package com.senlingspace.framework.web.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.senlingspace.common.utils.DateUtils;
import com.senlingspace.system.domain.FileDetail;
import com.senlingspace.system.mapper.FileDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.recorder.FileRecorder;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * 文件详情服务
 *
 * @author lebronjames
 * @date 2024/10/18
 */
@Slf4j
@Service
public class FileDetailService implements FileRecorder {

    @Autowired
    private FileDetailMapper fileDetailMapper;

    @Override
    public boolean save(FileInfo fileInfo) {
        log.info("上传信息记录：{}", JSON.toJSONString(fileInfo));
        if (Objects.isNull(fileInfo)) {
            return false;
        }

        FileDetail fileDetail = new FileDetail();
        BeanUtils.copyProperties(fileInfo, fileDetail);
        fileDetail.setId(UUID.randomUUID().toString().replaceAll("-", "").toLowerCase());
        fileDetail.setCreateTime(DateUtils.getNowDate());
        int insert = fileDetailMapper.insert(fileDetail);
        return insert == 1;
    }

    @Override
    public void update(FileInfo fileInfo) {

    }

    @Override
    public FileInfo getByUrl(String url) {
        if (StrUtil.isBlank(url)) {
            return null;
        }

        int lastIndex = url.lastIndexOf("/");
        if (lastIndex != -1 && lastIndex < url.length() - 1) {
            String filename = url.substring(lastIndex + 1);
            if (StrUtil.isBlank(filename)) {
                return null;
            }

            FileDetail fileDetail = new FileDetail();
            if (filename.endsWith(".min.jpg")) {
                fileDetail.setThFilename(filename);
            } else {
                fileDetail.setFilename(filename);
            }
            FileDetail detail = fileDetailMapper.selectOne(fileDetail);
            log.info("文件信息查询：{}", JSON.toJSONString(detail));
            if (Objects.isNull(detail)) {
                return null;
            }

            FileInfo fileInfo = new FileInfo();
            BeanUtils.copyProperties(detail, fileInfo);

            return fileInfo;
        }

        return null;
    }

    @Override
    public boolean delete(String url) {
        return false;
    }

    @Override
    public void saveFilePart(FilePartInfo filePartInfo) {

    }

    @Override
    public void deleteFilePartByUploadId(String uploadId) {

    }

}
